<script lang="ts" setup>
import { Bell, CircleCloseFilled, Guide } from "@element-plus/icons-vue";
import * as utils from "@/utils/utils";
import { sleep, tools } from "@/utils/utils";
import btn from "@/utils/buttonInterface";
import { ElMessage } from "element-plus";

// 常量

// 响应变量
let address: Ref<string>;
address = ref("");
const jsonRes = ref<Object>({});
const tableRes = ref<strPair[]>([]);
const loading = ref<boolean>(false);
const refreshLoading = ref<boolean>(false);

async function refreshPage() {
  refreshLoading.value = true;
  await sleep(1000);
  try {
    await btn.refreshPage();
    ElMessage({
      showClose: true,
      message: "尝试刷新缓存...",
      type: "warning",
      icon: Bell,
      duration: 3000,
    });
  } catch (error) {
    ElMessage({
      showClose: true,
      message: "缓存更新报错！！",
      type: "error",
      icon: CircleCloseFilled,
      duration: 3000,
    });
  }
  refreshLoading.value = false;
}

const requestAddrSeg = async () => {
  // 清空上一轮的数据
  jsonRes.value = {};
  tableRes.value = [];
  if (utils.Str_isEmpty(address.value)) return;

  // 开启的等待状态
  loading.value = true;
  try {
    let temp = await btn.addressServices(address.value);

    // 设置 json 格式的数据
    jsonRes.value = temp["data"];
    // 设置 表格 格式的数据
    tableRes.value = tools.getResultToTable(temp["data"]);

    loading.value = false;
  } catch (error) {
    jsonRes.value = {
      Error: "Error!",
      content: error,
    };
    loading.value = false;
  }
};
</script>

<template>
  <MainPage>
    <template v-slot:headerTitle>
      <Lv1stTitle title="地址分词" />
      <PrettyBtn2
        style="margin-left: auto"
        :loading="refreshLoading"
        :on-click="refreshPage"
        :btn-name="'RefreshCache'"
      />
    </template>
    <template v-slot:decoration>
      <TopBar />
    </template>
    <template v-slot:contents>
      <Contents>
        <template v-slot:inputComp>
          <MyInput
            v-model:value="address"
            input-tips="请输入完整地址..."
            btn-name="分词"
            :btn-icon="Guide"
            :loading="loading"
            :on-click-event="requestAddrSeg"
          />
        </template>
        <template v-slot:dataShow>
          <transition name="fade">
            <CarouselResView
              :show-data-json="jsonRes"
              :show-data-table="tableRes"
              :loading="loading"
              v-if="address != ''"
            />
          </transition>
          <transition name="fade">
            <TableLoading1
              class="donghua"
              :message="''"
              v-if="address === ''"
            />
          </transition>
        </template>
      </Contents>
    </template>
  </MainPage>
</template>

<style scoped>
.donghua {
  top: 50%;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
